Page({
  data: {
    title: '',
    categoryList: ['住院陪护', '院外陪护', '社会化转运', '陪检'],
    categoryValue: '',
    gender: '0',
    chargeType: '',
    address: '',
    intro: '',
    startTime: '',
    endTime: '',
    today: '',
    totalAmount: 0,
    amountDesc: '请选择计费方式和时间计算金额',
    isLoading: false,
    baseUrl: 'http://localhost:8080'
  },

  onLoad() {
    // 每次打开页面初始化表单数据
    this.initFormData();
  },

  // 初始化表单数据方法
  initFormData() {
    const now = new Date();
    const todayStr = `${now.getFullYear()}-${this.formatNum(now.getMonth() + 1)}-${this.formatNum(now.getDate())}`;
    
    // 清除本地缓存的表单数据
    wx.removeStorageSync('publishFormData');
    
    // 重置所有表单数据
    this.setData({ 
      today: todayStr,
      title: '',
      categoryValue: '',
      gender: '0',
      chargeType: '',
      address: '',
      intro: '',
      startTime: '',
      endTime: '',
      totalAmount: 0,
      amountDesc: '请选择计费方式和时间计算金额'
    });
  },

  formatNum(num) {
    return num < 10 ? `0${num}` : num;
  },

  bindTitleInput(e) {
    this.setData({ title: e.detail.value });
    this.saveFormData();
  },

  bindCategoryChange(e) {
    const index = e.detail.value;
    this.setData({ categoryValue: this.data.categoryList[index] });
    this.saveFormData();
  },

  bindGenderChange(e) {
    this.setData({ gender: e.detail.value });
    this.saveFormData();
  },

  bindChargeChange(e) {
    const chargeType = e.detail.value;
    this.setData({ chargeType }, () => {
      this.calculateAmount();
      this.saveFormData();
    });
  },

  bindAddressInput(e) {
    this.setData({ address: e.detail.value });
    this.saveFormData();
  },

  bindIntroInput(e) {
    this.setData({ intro: e.detail.value });
    this.saveFormData();
  },

  bindStartTimeChange(e) {
    const startTime = e.detail.value;
    if (this.data.endTime && this.data.endTime < startTime) {
      this.setData({ endTime: '' });
    }
    this.setData({ startTime }, () => {
      this.calculateAmount();
      this.saveFormData();
    });
  },

  bindEndTimeChange(e) {
    const endTime = e.detail.value;
    this.setData({ endTime }, () => {
      setTimeout(() => {
        this.calculateAmount();
        this.saveFormData();
      }, 100);
    });
  },

  calculateAmount() {
    const { startTime, endTime, chargeType } = this.data;
    
    const priceConfig = {
      fullDay: 200,
      perHour: 25,
      dayHour: 6
    };

    if (!chargeType) {
      this.setData({ 
        totalAmount: 0, 
        amountDesc: '请选择计费方式' 
      });
      return;
    }

    if (!startTime || !endTime) {
      this.setData({ 
        totalAmount: 0, 
        amountDesc: '请选择完整陪护日期' 
      });
      return;
    }

    const startMs = new Date(startTime).getTime();
    const endMs = new Date(endTime).getTime();
    
    if (isNaN(startMs) || isNaN(endMs) || endMs < startMs) {
      this.setData({ 
        totalAmount: 0, 
        amountDesc: '日期选择错误' 
      });
      return;
    }

    const dayDiff = Math.ceil((endMs - startMs) / (24 * 60 * 60 * 1000)) + 1;
    
    let totalAmount = 0;
    let amountDesc = '';
    
    if (chargeType === '0') {
      totalAmount = dayDiff * priceConfig.fullDay;
      amountDesc = `${dayDiff}天 × ${priceConfig.fullDay}元/天 = ${totalAmount}元`;
    } else {
      const totalHour = dayDiff * priceConfig.dayHour;
      totalAmount = totalHour * priceConfig.perHour;
      amountDesc = `${dayDiff}天 × ${priceConfig.dayHour}小时/天 × ${priceConfig.perHour}元/小时 = ${totalAmount}元`;
    }

    this.setData({
      totalAmount: totalAmount,
      amountDesc: amountDesc
    });
  },

  saveFormData() {
    const formData = {
      title: this.data.title,
      categoryValue: this.data.categoryValue,
      gender: this.data.gender,
      chargeType: this.data.chargeType,
      address: this.data.address,
      intro: this.data.intro,
      startTime: this.data.startTime,
      endTime: this.data.endTime
    };
    wx.setStorageSync('publishFormData', formData);
  },

  validateForm() {
    const { title, categoryValue, address, startTime, endTime, totalAmount } = this.data;
    
    if (!title.trim()) {
      wx.showToast({ title: '请输入标题', icon: 'none' });
      return false;
    }
    
    if (!categoryValue) {
      wx.showToast({ title: '请选择类别', icon: 'none' });
      return false;
    }
    
    if (!address.trim()) {
      wx.showToast({ title: '请输入地址', icon: 'none' });
      return false;
    }
    
    if (!startTime || !endTime) {
      wx.showToast({ title: '请选择陪护日期', icon: 'none' });
      return false;
    }
    
    if (totalAmount <= 0) {
      wx.showToast({ title: '金额计算异常', icon: 'none' });
      return false;
    }
    
    return true;
  },

  // 生成订单号
  generateOrderNo() {
    const now = new Date();
    const timestamp = now.getTime();
    const random = Math.floor(Math.random() * 1000);
    return `ORD${timestamp}${random}`;
  },

  // 映射前端类别到后端数字
  mapCategoryToBackend(category) {
    const categoryMap = {
      '住院陪护': 1,
      '院外陪护': 2, 
      '社会化转运': 3,
      '陪检': 4
    };
    return categoryMap[category] || 1;
  },

  // 构建请求数据 - 与后端字段完全对齐
  buildRequestData() {
    const { title, categoryValue, address, intro, startTime, endTime, totalAmount, chargeType, gender } = this.data;
    const userInfo = wx.getStorageSync('userInfo');
    return {
      orderNo: this.generateOrderNo(),
      userId: userInfo.userId || '', // 后续替换为真实登录用户ID
      nurseId: '', // 未选护工时可设为null（需后端允许）
      title: title,
      category: this.mapCategoryToBackend(categoryValue),
      serviceType: categoryValue,
      startDate: startTime + ' 00:00:00',
      endDate: endTime + ' 00:00:00',
      careLocation: address,
      address: address,
      careTime: '每天9:00-18:00',
      phone: '15190005987', // 后续替换为真实用户手机号
      description: intro || '无特殊要求',
      price: totalAmount,
      nurseName: '',
      userName: '',
      requiredGender: parseInt(gender, 10),
      orderStatus: 1 // 订单状态，默认设为1（待支付，需与后端确认状态值）
    };
  },

  // 调用后端接口
  async submitToBackend(orderData) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${this.data.baseUrl}/orders/add`,
        method: 'POST',
        data: orderData, 
        header: {
          'Content-Type': 'application/x-www-form-urlencoded' 
        },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data);
          } else {
            reject(new Error(`请求失败: ${res.statusCode}`));
          }
        },
        fail: (error) => {
          console.error('接口请求失败:', error);
          reject(error);
        }
      });
    });
  },

  // 提交表单（调用后端接口 + 跳转支付页）
  async submitForm() {
    if (!this.validateForm()) {
      return;
    }

    this.setData({ isLoading: true });

    try {
      // 1. 构建订单数据
      const requestData = this.buildRequestData();
      console.log('提交给后端的订单数据:', requestData);

      // 2. 调用后端接口
      const result = await this.submitToBackend(requestData);
      console.log('后端接口返回:', result);

      // 3. 接口调用成功后，提示并跳转支付页
      wx.showToast({ title: '订单提交成功', icon: 'success' });

      // 4. 清除表单缓存
      wx.removeStorageSync('publishFormData');

      // 5. 跳转到支付页（携带订单数据）
      setTimeout(() => {
        wx.navigateTo({
          url: `/pages/pay/pay?orderData=${encodeURIComponent(JSON.stringify(requestData))}`
        });
      }, 1500);

    } catch (error) {
      console.error('提交失败:', error);
      wx.showToast({ title: '发布失败，请重试', icon: 'none' });
    } finally {
      this.setData({ isLoading: false });
    }
  },

  onUnload() {
    // 页面卸载时保存表单数据（但下次打开会被初始化覆盖）
    this.saveFormData();
  }
});